package com.thorqq.translation.api;

import java.util.HashMap;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.thorqq.translation.utils.MD5;

public class TransBaidu extends TransApi
{
	private static final String	TRANS_API_HOST	= "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private static final String APP_ID = "20180904000202638";
    private static final String SECURITY_KEY = "S1s34N5esP9RNtXzYd7C";

	private String	            appid;
	private String	            securityKey;

	public TransBaidu()
	{
		this.appid = APP_ID;
		this.securityKey = SECURITY_KEY;
	}

	@Override
    public String enToZh(String src) throws Exception
    {
	    return translate("en", "zh", src);
    }

	@Override
    public String zhToEn(String src) throws Exception
    {
	    return translate("zh", "en", src);
    }
	
	@Override
    protected String translate(String from, String to, String src) throws Exception
    {		
		Map<String, String> params = buildParams(src, from, to);
		Connection conn = Jsoup.connect(TRANS_API_HOST);
		conn.data(params);
    	conn.ignoreContentType(true);
    	Document doc = conn.post();
    	
    	// {"error_code":"54001","error_msg":"Invalid Sign"}
    	// {"from":"en","to":"zh","trans_result":[{"src":"apple","dst":"\u82f9\u679c"}]}
    	
    	String dst = null;

    	String result = doc.body().text();
    	JSONObject json = JSON.parseObject(result);
    	String transResult = json.getString("trans_result");
    	if(transResult != null)
    	{
    		JSONArray array = JSON.parseArray(transResult);
    		dst = array.getJSONObject(0).getString("dst");
    	}
    	else
    	{
    		String errorCode = json.getString("error_code");
    		String errorMsg = json.getString("error_msg");
    		
    		throw new Exception("Baidu translation error: [" + errorCode + "]" + errorMsg);
    	}
    	
    	
		return dst;
    }

	private Map<String, String> buildParams(String query, String from, String to)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put("q", query);
		params.put("from", from);
		params.put("to", to);

		params.put("appid", appid);

		// 随机数
		String salt = String.valueOf(System.currentTimeMillis());
		params.put("salt", salt);

		// 签名
		String src = appid + query + salt + securityKey; // 加密前的原文
		params.put("sign", MD5.md5(src));

		return params;
	}

	@Override
    public String getVendor()
    {
	    return "Baidu";
    }

}
